//
//  MapView.swift
//  resumelist
//
//  Created by zhiyuwu on 2020/4/17.
//  Copyright © 2020 zhiyuwu. All rights reserved.
//

import SwiftUI
import MapKit
import UIKit
import CoreLocation

extension MKPointAnnotation {
    static var example: MKPointAnnotation {
        let annotation = MKPointAnnotation()
        annotation.title = "London"
        annotation.subtitle = "Home to the 2012 Summer Olympics."
        annotation.coordinate = CLLocationCoordinate2D(latitude: 51.5, longitude: -0.13)
        return annotation
    }
}

struct MapView: UIViewRepresentable {
    
    var newsListItem: NewsListItem
    
    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
        
        
        
        let posi = newsListItem.pos
                
        let pos = posi.components(separatedBy: ",")
                
        let lati = (pos[0] as NSString).doubleValue
        
        let long = (pos[1] as NSString).doubleValue
        
        let mapView = MKMapView()
        
        
        let objectAnnotation = MKPointAnnotation()
        objectAnnotation.coordinate = CLLocation(latitude: lati, longitude: long).coordinate
        objectAnnotation.title = newsListItem.title
        objectAnnotation.subtitle = newsListItem.summary
        
        mapView.addAnnotation(objectAnnotation)
        
        return mapView
    }
    
    func updateUIView(_ uiView: MKMapView, context: Context) {
        
        let posi = newsListItem.pos
                
        let pos = posi.components(separatedBy: ",")
                
        //        let lati = pos[0]
        //        let long = pos[1]
                
        let lati = (pos[0] as NSString).doubleValue
        
        let long = (pos[1] as NSString).doubleValue
        
        let coordinate = CLLocationCoordinate2D(
            latitude: lati, longitude: long)
        let span = MKCoordinateSpan(latitudeDelta: 0.015, longitudeDelta: 0.015)
//        let region = MKCoordinateRegion(center: coordinate, span: span)
        
        
        uiView.showsUserLocation = true
        
        let region = MKCoordinateRegion(center: uiView.userLocation.location?.coordinate ?? coordinate, span: span)
        
        uiView.setRegion(region, animated: true)
        
        
       

       
    }
}

struct MapView_Previews: PreviewProvider {
    static var previews: some View {
        MapView(newsListItem: newsList[0])
    }
}
